import { loginApi, logout, getUserInfoApi } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";
import { constantRoutes } from "@/router";

// const getDefaultState = () => {
//   return {
//     token:null
//   };
// };

const state = {
  token: getToken(),
  userInfo: {},
  routes: [],
};

const mutations = {
  //保存token
  setToken(state, data) {
    //保存到vuerx的state中
    state.token = data;
    //数据持久化
    setToken(data);
  },
  //清除token
  removeToken(state) {
    state.token = null;
    //删除本地token
    removeToken();
  },
  //保存用户信息
  setUserInfo(state, data) {
    state.userInfo = data;
  },
  //设置路由
  setRoute(state, newRoutes) {
    //state.routes=[静态路由,动态路由]
    console.log("newRoutes:", newRoutes);
    state.routes = [...constantRoutes, ...newRoutes];
  },
};

const actions = {
  //登录
  async login(context, data) {
    //调用后端登录接口,如果成功返回res=token
    const res = await loginApi(data); //res=1232456

    context.commit("setToken", res);
  },

  // 获取用户信息
  async getInfo(context) {
    console.log("11111");
    //调用获取用户信息的接口
    const res = await getUserInfoApi();
    context.commit("setUserInfo", res);

    return res;
  },

  // 登出
  logout(context) {
    context.commit("removeToken");
    context.commit("setUserInfo", {});
  },

  // 删除token
  resetToken({ commit }) {},
};

export default {
  //全名空间
  namespaced: true,
  state,
  mutations,
  actions,
};
